#include <stdio.h>
#include <stack>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <stdio.h>
#include <math.h>

//https://mp.weixin.qq.com/s/48jMBVVEqQp3IR6NpUy2QA

using namespace cv;
using namespace std;

typedef unsigned char U_CHAR;

int main(int argc, char* argv[]) {


    CvSize sz;
    sz.height = 300;
    sz.width = 300;


    // 生成list方式　ls frame | sed "s:^:./frame/:" >> list.txt

    system("mkdir ./image");
    ifstream fin("list.txt"); // 图片名字列表
    string inputname_string;


    while (getline(fin,inputname_string))
    {
        const char *inputname_char = (const char *)inputname_string.data();
        cout << "inputname_string:" << inputname_string << endl;

        string input_first_name = inputname_string.substr(0, inputname_string.rfind("."));
        input_first_name = input_first_name.erase(0,7);
        input_first_name = "./image" + input_first_name + ".bgr";
        cout << "input_first_name:" << input_first_name << endl;

        const char *outname = input_first_name.data();

        // src
        IplImage *src = 0;
        src = cvLoadImage(inputname_char, 1);

        cvShowImage("src",src);
//        cvWaitKey(0);

        // resize
        IplImage *img;
        if(src)
        {
            img = cvCreateImage(sz,src->depth,src->nChannels);
            cvResize(src,img,CV_INTER_CUBIC);
            cvShowImage("img",img);
            cvWaitKey(0);
        }

        if (img == 0) {
            printf("Load image error\n");
            return -1;
        }

        // transform
        U_CHAR *data = (U_CHAR*)img->imageData;
        int step = img->widthStep; // 图片一行里的 bytes(8bit) 大小，包括所有通道，一般3xwidth bytes
        printf("widthStep: %d, height: %d, width: %d\n",
               step, img->height, img->width);

        // bgr
        FILE *fp = fopen(outname, "wb");
        for (int cc=0; cc<img->nChannels; cc++) {
            for (int hh=0; hh<img->height; hh++) {
                for(int ww=0; ww<img->width; ww++) {
                    // mg->widthStep为图片一行里的 bytes(8bit) 大小，包括所有通道，一般3xwidth bytes
                    fwrite(&data[hh*img->widthStep + ww*img->nChannels + cc], sizeof(U_CHAR), 1, fp);
                }
            }
        }
        fclose(fp);

        // 网络只能输入bgr格式的数据流？(因为是按照bgr训练的？yuv格式是否有转换？)
        // jpg读取后，数据存放在 imageData 里
        // imageData格式：读取每个像素点里不同通道的值，再依次读完所有像素点
        // bgr格式：先在b通道里顺序读取所有像素的数据，再继续读取g和r通道的，每像素通道8bit
        // yvu422(YCbCr422)：先存所有Y，再存v和u，v在前u在后
    }


    return 0;
}






